#!/usr/bin/python
###################################################################################################                                                                                              
#                                                                                              
# DEVELOPERS : Luca Sanna                                                                        
# VERSIONE : 0.1                                                                                  
#                                                                                                                    
# E-MAIL: sanluca78@gmail.com                                                                                        
# COPYRIGHT: (c) 2015                                                                      
# PROGRAMMA: Py-Home-Slave  
#This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.                                                                          
###################################################################################################
import time,sys,math,smtplib
from ablib import DS18B20
from threading import Thread
from database import *
from tools import *
from si import *
from subclass import *
from pub import *
import paho.mqtt.client as mqtt
class MyStorage(Thread):
    time.sleep(1)
    db=Mydata()
    s1 = Si7005()
    lista=[]
    lista1=[]
    lista2=[]
    listaenel=[]
    midnight=0
    time.sleep(2)
    mq=MyPub()
    x=db.view_name()
    nome=str(x[1])
    
    def sensor(self):
        x=self.db.view_sensor()
        self.si = x[1]
        self.da = x[2]
    def archive(self):
        a=self.db.view_archive()
        self.arch=a[1]
    
    def si7005(self):

        z=1
        # short methods:
        #print "Hum: %.2f Temp: %.2f" % (s1.getH() , s1.getT())
        #print "Hum: %.2f Temp: %.2f" % s1.getHT()
        while True:
            z+=1
            try:
                self.temp= "%.2f" % self.s1.getT()
                self.umidita= "%.2f" % self.s1.getH()
                
                self.db.update_real_time('temp',float(self.temp))
                self.db.update_real_time('umid',float(self.umidita))
                self.mq.pub('home/%s/temperatura' %self.nome ,'%s' %str(self.temp))
                self.mq.pub('home/%s/umidita' %self.nome,'%s' %str(self.umidita))
                #logCritical("topic %s nome %s temp % umid %s" %(self.nome,self.nome,self.temp,self.umidita))
            	break
            except Exception,e:
                logCritical("except si %s" %e)
                if z==3:
                    self.temp=0
                    self.umidita=0
                    break
    
    def dallas(self):
        a=self.db.view_sensor()
        b=a[3]
        z=1
        while True:
            z+=1
            try:
                #1-wire pin 35
                sensor = DS18B20("%s" %b)
                self.actual1 = sensor.getTemp()
                self.actual = "%.02f" %self.actual1
                if self.actual == None:
                    pass
                else:
                    self.db.update_real_time('temp_d',float(self.actual))
                    self.mq.pub('home/%s/temperatura' %self.nome,'%s' %str(self.actual))
                    break
            except Exception,e:
                logCritical("except dallas %s" %e)
                if z==3:
                    self.actual=0
                    break
                   
    def phmeter(self):
        #lettura conversione ph
        #10 bit 1024
        x = self.db.view_calph()
        offset=float(x[1])
        VREF=5.089
        VREF_MAX=1.63
        Fattore_conversione=3.13
        volt_per_point=3.3/2**10
        while True:
            try:
                path="/sys/bus/iio/devices/iio:device0/in_voltage0_raw"
                fd = open(path,"r")
                self.ph1 = fd.read()
                fd.close()
                VREF_ADC=volt_per_point*int(self.ph1)
                #logCritical("VREF_ADC %s" %VREF_ADC)
                VREF_PHMETER=VREF_ADC*3.13
                #logCritical("vref_phmeter %s" %VREF_PHMETER)
                self.ph2=offset+(3.5*VREF_PHMETER)
                #logCritical("ph %s" %self.ph)
                #fd.close()
                self.ph = "%.02f" %self.ph2
                #logCritical("ph %s" %self.ph)
                if self.ph == None:
                    pass
                else:
                    self.db.update_real_time('ph',float(self.ph))
                    break
            except Exception,e:
                logCritical("except phmeter %s" %e)
                pass
    def imp_enel(self):
        b=self.db.view_real_time()
        self.enel=b[4]
    
    def imp_gas(self):
        pass
    
    def imp_acqua(self):
        pass
    
    def insert_storage(self,temp,umidita,temp_d,vento,rain,enel,gas,acqua,hour,day,month,year,lu):
        if self.arch==1:
            self.db.save_storage(temp,umidita,temp_d,vento,rain,enel,gas,acqua,hour,day,month,year,lu)
        
    def Media(self,numeri):
        if not numeri:
            return None
        somma = 0
        for num in numeri:
            somma += num
        self.media= float(somma) / len(numeri)
   
    def run(self):
        while True:
            self.archive()
            actualTime=time.localtime()
            year=actualTime[0]
            month=actualTime[1]
            day  =actualTime[2]
            hour =actualTime[3]
            minute=actualTime[4]
            self.imp_enel()
            self.sensor()
            if self.da==1:
                self.dallas()
            else:
                self.actual=0
            #self.phmeter()
            if self.si==1:
                self.si7005()
            else:
                self.temp=0
                self.umidita=0
                
            self.lista.append(float(self.temp))
            self.lista1.append(float(self.umidita))
            self.lista2.append(float(self.actual))
            self.listaenel.append(float(self.enel))
           
            if minute!=0:
                if self.midnight==0:
                    pass
                else:
                    self.midnight=0
            else:
                if self.midnight==0:
                    self.Media(self.lista)
                    temp="%.02f" % self.media
                    self.Media(self.lista1)
                    umidita="%.02f" %self.media
                    self.Media(self.lista2)
                    temp_d="%.02f" %self.media
                    vento=0
                    rain=0
                    self.Media(self.listaenel)
                    enel="%.02f" %self.media
                    gas=0
                    acqua=0
                    lu = len(self.lista)
                #self.insert_storage(day,month,year, hour, float(media1), float(minu), float(maxi) ,lu)
                    self.insert_storage(float(temp), float(umidita), float(temp_d),vento,rain,float(enel),gas,acqua,hour,day,month,year,lu)
                    self.lista=[]
                    self.lista1=[]
                    self.lista2=[]
                    self.midnight=1

            time.sleep(60)
